package t.l.component;

import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class InfoLabel extends JPanel {
  JTextField descriptionText, valueText, unitText;

  public InfoLabel(String description, int value, String unit) {
    setLayout(new GridLayout(1, 3));
    initView();
    setDescription(description);
    setUnit(unit);
    setValue(value);
  }

  private void initView() {
    descriptionText = new JTextField();
    valueText = new JTextField();
    unitText = new JTextField();

    valueText.addKeyListener(new KeyAdapter() {
      @Override public void keyTyped(KeyEvent e) {
        int keyChar = e.getKeyChar();
        if (keyChar < KeyEvent.VK_0 || keyChar > KeyEvent.VK_9) {
          e.consume();
        }
      }
    });

    descriptionText.setHorizontalAlignment(SwingConstants.RIGHT);
    descriptionText.setBackground(null);
    descriptionText.setBorder(null);
    descriptionText.setEnabled(false);

    unitText.setHorizontalAlignment(SwingConstants.LEFT);
    unitText.setBackground(null);
    unitText.setBorder(null);
    unitText.setEnabled(false);

    add(descriptionText);
    add(valueText);
    add(unitText);
  }

  public void setValue(int value) {
    valueText.setText(String.valueOf(value));
  }

  public void setUnit(String unit) {
    unitText.setText(unit);
  }

  public int getValue() {
    return valueText.getText().trim().isEmpty() ? 0 : Integer.parseInt(valueText.getText());
  }

  public void setDescription(String description) {
    descriptionText.setText(description);
  }

  public void setValueTextEnabled(boolean enabled) {
    valueText.setEnabled(enabled);
  }
}